package cn.t222.app.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.t222.app.pojo.DevUser;
import cn.t222.app.service.DevUserService;

@Controller
@RequestMapping("/devUsers")
public class DevUserController {
	private Logger log = Logger.getLogger(getClass());
	@Autowired private DevUserService devUserService;
	/**
	 * 查询所有,get  /devUsers
	 * @return
	 */
	@RequestMapping(value="", method={RequestMethod.GET})
	public String getAll(Model model) {
		model.addAttribute("devUsers", devUserService.getAll());
		return "user/list";
	}
	/**
	 * 添加,post  /devUsers
	 * @return
	 */
	@RequestMapping(value="", method={RequestMethod.POST})
	public String add(DevUser devUser) {
		devUserService.add(devUser);
		if(log.isDebugEnabled()) {
			log.debug("id===" + devUser.getId());
		}
		return "redirect:/devUsers";
	}
	/**
	 * 跳转到添加页面,get  /devUsers
	 * @return
	 */
	@RequestMapping(value="/add", method={RequestMethod.GET})
	public String add() {
		return "user/add";
	}
	@RequestMapping(value="/{id}", method={RequestMethod.GET})
	@ResponseBody
	public DevUser view(@PathVariable Long id) {
		return devUserService.get(id);
	}
	@RequestMapping(value="/del/{id}", method={RequestMethod.GET})
	@ResponseBody
	public boolean del(@PathVariable Long id) {
		return devUserService.del(id)>0;
	}
	
	@RequestMapping(value="/update/{id}", method={RequestMethod.GET})
	public ModelAndView update(@PathVariable Long id) {
		ModelAndView mav = new ModelAndView("user/update");
		mav.addObject(devUserService.get(id));
		return mav;
	}
	@RequestMapping(value="/update/{id}", method={RequestMethod.POST})
	public String update(@PathVariable Long id, DevUser devUser) {
		Assert.notNull(id, "id不能为空");
		devUser.setId(id);
		devUserService.update(devUser);
		return "redirect:/devUsers";
	}
}
